package org.vt.scheduleapp;

import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.List;

import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.TimePicker;

public class AddEventActivity extends Activity{

	public static String soundMode;
	String selectedProfile;
	
	public void onCreate(Bundle savedInstanceState){
		final Context ctx = this;
		super.onCreate(savedInstanceState);
		setContentView(R.layout.add_event);
		
		final EditText eventName = (EditText) findViewById(R.id.eventName); //event name text field
		final DatePicker startDay = (DatePicker) findViewById(R.id.startDay);
		final DatePicker endDay = (DatePicker) findViewById(R.id.endDay);
		final TimePicker startTime = (TimePicker) findViewById(R.id.startTime);
		final TimePicker endTime = (TimePicker) findViewById(R.id.endTime);
		

		//gets the event name, if available, and updates the event name text box
		
		//String name = getIntent().getParcelableExtra("eventName");
		eventName.setText("Enter the event name here");
		String name = (String) getIntent().getSerializableExtra("eventName");
		//Log.v("Intent Event Name", name);
		eventName.setText(name);
		
		
		//gets the event start date info, if available, and updates the start day DatePicker
		String startYearString = (String) getIntent().getSerializableExtra("startYear");
		int startYear = Integer.parseInt(startYearString);
		String startMonthString = (String) getIntent().getSerializableExtra("startMonth");
		int startMonth = Integer.parseInt(startMonthString) - 1;
		String startDayString = (String) getIntent().getSerializableExtra("startDay");
		int startDayNum = Integer.parseInt(startDayString);
		
		Log.v("Intent Event Year", startYearString);
		Log.v("Intent Event Month", startMonthString);
		Log.v("Intent Event Month", startDayString);
		
		
		startDay.updateDate(startYear, startMonth, startDayNum);
		
		
		
		//gets the event end date info, if available, and updates the end day DatePicker
		String endYearString = (String) getIntent().getSerializableExtra("endYear");
		int endYear = Integer.parseInt(endYearString);
		String endMonthString = (String) getIntent().getSerializableExtra("endMonth");
		int endMonth = Integer.parseInt(endMonthString) - 1;
		String endDayString = (String) getIntent().getSerializableExtra("endDay");
		int endDayNum = Integer.parseInt(endDayString);
		endDay.updateDate(endYear, endMonth, endDayNum);
		
		//gets the event start time info, if available, and updates the start time TimePicker
		
		String startHourString = (String) getIntent().getSerializableExtra("startHour");
		int startHour = Integer.parseInt(startHourString);
		String startMinString = (String) getIntent().getSerializableExtra("startMin");
		int startMin = Integer.parseInt(startMinString);
		startTime.setCurrentHour(startHour);
		startTime.setCurrentMinute(startMin);
		
		Log.v("Intent Event Hour", startHourString);
		Log.v("Intent Event Min", startMinString);
		
		
		
		//gets the event end time info, if available, and updates the end time TimePicker
		String endHourString = (String) getIntent().getSerializableExtra("endHour");
		int endHour = Integer.parseInt(endHourString);
		String endMinString = (String) getIntent().getSerializableExtra("endMin");
		int endMin = Integer.parseInt(endMinString);
		endTime.setCurrentHour(endHour);
		endTime.setCurrentMinute(endMin);
		
		
		Button confirmEvent = (Button) findViewById(R.id.confirm); //confirm event button
		Button cancel = (Button) findViewById(R.id.cancel);
		
	
		//drop down menu for determining repeat events
		final Spinner repeatOptions = (Spinner) findViewById(R.id.repeatOptions);
		ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
				this, R.array.repeatOptions, android.R.layout.simple_spinner_item);
		adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		repeatOptions.setAdapter(adapter);
		

	    final Spinner soundProfile = (Spinner) findViewById(R.id.ringerProfile);
	    
	    soundProfile.setOnItemSelectedListener(new 
	    		OnItemSelectedListener(){

					public void onItemSelected(AdapterView<?> parent, View view,
							int pos, long id) {
						selectedProfile = parent.getItemAtPosition(pos).toString();
					}

					public void onNothingSelected(AdapterView<?> arg0) {						
					}});
		
	    LocReader reader = new LocReader(this);
		List<Loc> locs = new ArrayList<Loc>();
		try {
			locs = reader.getAllLocs();
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e1) {
			e1.printStackTrace();
		}
		final Spinner locationPicker = (Spinner) findViewById(R.id.locationPicker);
		String[] locNames = new String[locs.size()];
		int count = 0;
		for(Loc l: locs)
		{
			locNames[count]=l.getName();
			count++;
		}
		ArrayAdapter<CharSequence> adapter2 = new ArrayAdapter<CharSequence>(this, android.R.layout.simple_spinner_item, locNames);
		adapter2.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
		locationPicker.setAdapter(adapter2);

		//When the confirm button is clicked the corresponding event information is collected
		confirmEvent.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				
				String eventTitle = eventName.getText().toString(); //returns event name
	
		
				int startDayOfMonth = startDay.getDayOfMonth();	// returns the day of the month as an integer
				String startDayString = "" + startDayOfMonth; // converts the integer to a string
				int startMonth = startDay.getMonth(); //returns the month of the year as an integer
				String startMonthString = "" + (startMonth+1); 
				int startYear = startDay.getYear(); //returns the year of the event as an integer
				String startYearString = "" + startYear; 
				String startDate = startMonthString+"/"+startDayString+"/"+startYearString;
				
				
				int endDayOfMonth = endDay.getDayOfMonth();	
				String endDayString = "" + endDayOfMonth;
				int endMonth = endDay.getMonth();	
				String endMonthString = "" + (endMonth+1);
				int endYear = endDay.getYear();	
				String endYearString = "" + endYear;
				String endDate = endMonthString+"/"+endDayString+"/"+endYearString;
				
				
				
				int startHour = startTime.getCurrentHour(); //returns the starting hour of the event, in 24 time, as an integer
				String startHourString = "" + startHour; 
				int startMinute = startTime.getCurrentMinute(); //return the starting minute as an integer
				String startMinuteString = "" + startMinute;
				if(startMinuteString.equals("0"))
				{
					startMinuteString = "00";
				}
				String startTime = startHourString+":"+startMinuteString;
				
				
				
				int endHour = endTime.getCurrentHour(); 
				String endHourString = "" + endHour; 
				int endMinute = endTime.getCurrentMinute(); 
				String endMinuteString = "" + endMinute;
				if(endMinuteString.equals("0"))
				{
					endMinuteString = "00";
				}
				String endTime = endHourString+":"+endMinuteString;
				
				
				String repeat = repeatOptions.getSelectedItem().toString(); //returns the selected repeat option as a string
				String locName = locationPicker.getSelectedItem().toString();

				CalendarEvent event = new CalendarEvent(eventTitle, startDate, endDate, startTime, endTime, repeat, locName);
				EventReader reader = new EventReader(ctx);
		
				List<CalendarEvent> events = new ArrayList<CalendarEvent>();
				try {
					events = reader.getAllEvents();
				} catch (IOException e) {
					
					e.printStackTrace();
				}
				events.add(event);
				EventWriter writer = new EventWriter(ctx);
				try {
					writer.writeEvent(events);
				} catch (IOException e) {
					
					e.printStackTrace();
				}
				
				//Alarm Code Block for Setting up an Event Sound Profile
				Intent alarmIntent = new Intent(AddEventActivity.this,SoundReceiver.class);
				PendingIntent pendingIntent = PendingIntent.getService(AddEventActivity.this, 12345, alarmIntent, PendingIntent.FLAG_CANCEL_CURRENT);
				
				AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
				
				//Create another calendar. Set its current time to the time selected in the TimePicker
                Calendar cal = new GregorianCalendar();
                
                cal.set(Calendar.YEAR,startYear);
                cal.set(Calendar.MONTH, startMonth);
                cal.set(Calendar.DAY_OF_MONTH,startDayOfMonth);
                cal.set(Calendar.HOUR_OF_DAY, startHour);
                cal.set(Calendar.MINUTE, startMinute);
                cal.set(Calendar.SECOND, 0);
                
                //Reset to Full Sound at End Event Time
                Intent alarmIntent2 = new Intent(AddEventActivity.this,SoundReset.class);
				PendingIntent pendingIntent2 = PendingIntent.getService(AddEventActivity.this, 54321, alarmIntent2, PendingIntent.FLAG_CANCEL_CURRENT);
                
				Calendar cal2 = new GregorianCalendar();
                cal2.set(Calendar.YEAR,endYear);
                cal2.set(Calendar.MONTH, endMonth);
                cal2.set(Calendar.DAY_OF_MONTH,endDayOfMonth);
                cal2.set(Calendar.HOUR_OF_DAY, endHour);
                cal2.set(Calendar.MINUTE, endMinute);
                cal2.set(Calendar.SECOND, 0);
                
                //Get the difference between the current time and the desired time for the profile
                long desiredMillis = cal.getTimeInMillis();
                long currentMillis = System.currentTimeMillis();
                long millisDifference = desiredMillis - currentMillis;
                
              //Get the difference between the current time and the desired end time for the profile
                long desiredMillis2 = cal2.getTimeInMillis();
                long currentMillis2 = System.currentTimeMillis();
                long millisDifference2 = desiredMillis2 - currentMillis2;
                
                //Read the User Selection
                Spinner modeSpinner = (Spinner) findViewById(R.id.ringerProfile);
                soundMode = (String) modeSpinner.getSelectedItem();
                
                //Set the AlarmManager to start the profile at the specified time
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millisDifference, pendingIntent);
                //Set the AlarmManager to end the profile at the specified time
                alarmManager.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + millisDifference2, pendingIntent2);
				
                AddEventActivity.this.finish();//after all the information is collected the user is taken back to the schedule
			}
		});
		
		
		//When the cancel button is clicked the user is taken back to the previous screen
		cancel.setOnClickListener(new View.OnClickListener() {
			
			public void onClick(View v) {
				AddEventActivity.this.finish();
			}
		});
		
		
	}
}
